package com.example.controller;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.example.Constants;
import com.example.Util;

public class Controller extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected HashMap<String, ActionServlet> events = new HashMap<String, ActionServlet>();

	@Override
	public void init() throws ServletException {
		ResourceBundle bundle = ResourceBundle.getBundle("com.example.Action");
		Enumeration<String> e = bundle.getKeys();
		while (e.hasMoreElements()) {
			String key = (String) e.nextElement();
			String value = bundle.getString(key);

			try {

				ActionServlet event = (ActionServlet) Class.forName(value)
						.newInstance();
				events.put(key, event);

			} catch (Exception ex) {
				ex.printStackTrace();
			}
			// Logger for webapplication

			/*
			 * Enumeration servletParams = this.getInitParameterNames(); while
			 * (servletParams.hasMoreElements()) { String aName = (String)
			 * servletParams.nextElement(); String aValue =
			 * this.getInitParameter(aName);
			 * 
			 * Logger.info("Servlet Parameter name:" + aName + ", value:" +
			 * aValue); }
			 * 
			 * 
			 * ServletContext sc = getServletContext(); Enumeration webappParams
			 * = sc.getInitParameterNames(); while
			 * (webappParams.hasMoreElements()) { String wName = (String)
			 * webappParams.nextElement(); String wValue =
			 * sc.getInitParameter(wName);
			 * 
			 * Logger.info("Webapp parameter name:" + wName + ", value:" +
			 * wValue); }
			 */

		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String targetURL = "";
		req.setCharacterEncoding("utf-8");	
		String event = validationEven(req);
		ActionServlet action = getEventHandler(event);
		try {
			// Session check
			if (!isSession(event, req, targetURL)) {
				action = getEventHandler(Constants.SESSION_OUT_ACTION);
			}

			// jsp file check
			String realFile = req.getSession().getServletContext()
					.getRealPath(targetURL);
			File f = new File(realFile);
			if (!f.exists()) {
				req.setAttribute("error", realFile + " do not exist.");
				action = getEventHandler(Constants.ERROR_ACTION);
			}

			action.process(getServletContext(), req, resp);

		} catch (MissingResourceException mre) {
			req.setAttribute("error", mre.toString());
			action = getEventHandler(Constants.ERROR_ACTION);
			try {
				action.process(getServletContext(), req, resp);
			} catch (Exception xe) {
			}
		} catch (Exception e) {
			System.out.println("Controll error = " + e.toString());

			req.setAttribute("error", e.toString());
			action = getEventHandler(Constants.ERROR_ACTION);
			try {
				action.process(getServletContext(), req, resp);
			} catch (Exception xe) {
			}
		} finally {
			action.forward(req, resp);
		}
	}

	/**
	 * @comment : Session check
	 */
	protected boolean isSession(String event, HttpServletRequest req,
			String targetURL) {
		boolean isSession = true;
		boolean sessionYn = true;

		HttpSession session = req.getSession();

		String liveYn = (String) session.getAttribute("ses_check");
		if (Util.isNotNull(liveYn)) {
			sessionYn = false;
		}

		if (sessionYn) {
			// session not check
			if (event != null && !event.equals(Constants.ERROR_ACTION)
					&& !event.equals(Constants.UNKNOWN_ACTION)
					&& !event.equals(Constants.SESSION_OUT_ACTION)
					&& !event.equals(Constants.LOGIN_FORM_ACTION)
					&& !event.equals(Constants.LOGIN_PROC_ACTION)
					&& !event.equals(Constants.LOGOUT_ACTION)) {
				isSession = false;
			}
		}

		return isSession;
	}

	private ActionServlet getEventHandler(String event) {
		ActionServlet h;
		try{
			h = events.get(event);
		}catch(Exception ex)
		{
			h = events.get("UNKNOWN_ACTION");
			ex.printStackTrace();
		}
		return h;
	}

	private String validationEven(HttpServletRequest req) {
		String e = req.getParameter("do");
		if(e==null || !events.containsKey(e)){
			e = "UNKNOWN_ACTION";
		}
		return e;
	}
}
